package main

import (
	"fmt"
	"sync"
	"strconv"
	bc "./blockchain"
	nt "./network"
)

const (
	ADDRESS = ":8080"
)

const (
	ADD_DATA = iota + 1
	GET_BLOCK
)

var (
	mutex sync.Mutex
	Chain = bc.NewChain()
)

func main() {
	nt.Listen(ADDRESS, handleServer)
	for {
		fmt.Scanln()
	}
}

func handleServer(conn nt.Conn, pack *nt.Package) {
	nt.Handle(ADD_DATA, conn, pack, handleAddData)
	nt.Handle(GET_BLOCK, conn, pack, handleGetBlock)
}

func handleAddData(pack *nt.Package) string {
	mutex.Lock()
	Chain = append(Chain, bc.NewBlock(pack.Data, Chain[len(Chain)-1].CurrHash))
	mutex.Unlock()
	return "ok"
}

func handleGetBlock(pack *nt.Package) string {
	num, err := strconv.Atoi(pack.Data)
	if err != nil {
		return "fail"
	}
	if num < 0 || num >= len(Chain) {
		return "fail"
	}
	return bc.SerializeBlock(Chain[num])
}
